// api/handlers/user_handler.go
package handlers

import (
	"mygin/internal/models"
	"mygin/internal/services"
	"net/http"
	"strconv"
	"time"

	"mygin/pkg/httpclient"
	"mygin/pkg/response"

	"github.com/gin-gonic/gin"
)

type UserHandler struct {
	service *services.UserService
}

func NewUserHandler(service *services.UserService) *UserHandler {
	return &UserHandler{service: service}
}

// CreateUser 创建新用户
// @Summary 创建用户
// @Description 注册一个新用户账号
// @Tags 用户管理
// @Accept json
// @Produce json
// @Param user body models.UserCreateRequest true "用户信息"
// @Example request {"username": "john_doe", "password": "123456", "email": "john@example.com"}
// @Success 200 {object} models.User"创建成功"
// @Failure 400 {object} response.ErrorResponse "请求参数错误"
// @Failure 500 {object} response.ErrorResponse "服务器内部错误"
// @Router /api/v1/users [post]
func (h *UserHandler) CreateUser(c *gin.Context) {
	var user models.User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := h.service.RegisterUser(&user); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, response.Success("success", user))
}

// GetUser 获取用户信息
// @Summary 通过ID获取用户信息(V1)
// @Description 根据用户ID获取详细的用户信息
// @Tags 用户管理
// @Accept json
// @Produce json
// @Param id path int true "用户ID" Format(uint64)
// @Success 200 {object} models.User
// @Failure 400 {object} response.ErrorResponse "无效的ID格式或用户不存在"
// @Router /api/v1/users/{id} [get]
func (h *UserHandler) GetUser(c *gin.Context) {
	idStr := c.Param("id")

	// 将字符串ID转换为uint
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID format"})
		return
	}

	// 调用服务层
	user, err := h.service.GetUserByID(uint(id))
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Fail(400, "user not found"))
		return
	}
	c.JSON(http.StatusOK, response.Success("success", user))
}

// @Summary 获取用户列表(V1)
// @Description 获取分页用户列表
// @Tags  用户管理
// @Accept json
// @Produce json
// @Param page query int false "页码" default(1)
// @Param page_size query int false "每页数量" default(10)
// @Param username query string false "用户名筛选"
// @Param email query string false "邮箱筛选"
// @Failure 400 {object} map[string]string "参数错误"
// @Failure 500 {object} map[string]string "内部错误"
// @Router /api/v1/users [get]
func (h *UserHandler) ListUsers(c *gin.Context) {
	// 获取分页参数
	page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err != nil || page < 1 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid page parameter"})
		return
	}

	pageSize, err := strconv.Atoi(c.DefaultQuery("page_size", "10"))
	if err != nil || pageSize < 1 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid page_size parameter"})
		return
	}

	// 获取筛选条件
	filter := services.UserFilter{
		Username: c.Query("username"),
		Email:    c.Query("email"),
	}

	// 调用服务层获取用户列表和总数
	users, total, err := h.service.ListUsers(page, pageSize, filter)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 使用公共分页响应
	c.JSON(http.StatusOK, response.Success("success", response.NewPaginationResponse(total, page, pageSize, users)))
}

// UpdateUser 更新用户信息
// @Summary 更新用户信息(V1)
// @Tags  用户管理
// @Param id path int true "用户ID"
// @Param user body models.UserCreateRequest true "用户更新数据"
// @Success 200 {object} models.User
// @Router /api/v1/users/{id} [put]
func (h *UserHandler) UpdateUser(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "invalid ID format"})
		return
	}

	// 根据HTTP方法决定是全量还是部分更新
	if c.Request.Method == http.MethodPut {
		// PUT - 全量更新
		var user models.User
		if err := c.ShouldBindJSON(&user); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		user.ID = uint(id)
		err = h.service.UpdateUser(&user)
	} else {
		// PATCH - 部分更新
		var updateData map[string]interface{}
		if err := c.ShouldBindJSON(&updateData); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		err = h.service.UpdatePartial(uint(id), updateData)
	}

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, response.Success("success", ""))
}

// DeleteUser 删除用户
// @Summary 删除用户(V1)
// @Tags  用户管理
// @Description 删除用户(软删除)
// @Param id path int true "用户ID"
// @Success 200 {object} models.User "成功返回"
// @Failure 400 {object} map[string]string "参数错误"
// @Router /api/v1/users/{id} [delete]
func (h *UserHandler) DeleteUser(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "invalid ID format"})
		return
	}

	if err := h.service.DeleteUser(uint(id)); err != nil {
		switch err.Error() {
		case "user not found":
			c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
		default:
			c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
		}
		return
	}
	c.JSON(http.StatusOK, response.Success("success", ""))
}

/**************非curd方法区************************************/
func (h *UserHandler) GetExternalData(c *gin.Context) {
	// 创建客户端
	client := httpclient.NewCurl().
		SetTimeout(5*time.Second).
		SetHeader("Authorization", "Bearer your-token")

	// 发送GET请求
	resp, err := client.Get("https://api.example.com/data", nil)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 解析响应
	var result map[string]interface{}
	if err := resp.JSON(&result); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, result)
}

func (h *UserHandler) CreateExternalData(c *gin.Context) {
	var input struct {
		Name  string `json:"name"`
		Value string `json:"value"`
	}

	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 创建客户端
	client := httpclient.NewCurl().
		SetTimeout(5*time.Second).
		SetHeader("Content-Type", "application/json")

	// 发送POST请求
	resp, err := client.Post("https://api.example.com/data", input)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if !resp.IsOK() {
		body, _ := resp.Text()
		c.JSON(http.StatusInternalServerError, gin.H{"error": body})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"message": "Data created successfully"})
}

// GetUserByUsername 通过用户名获取用户信息
// @Summary 通过用户名获取用户信息
// @Description 根据用户名获取详细的用户信息
// @Tags 用户管理
// @Accept json
// @Produce json
// @Param username path string true "用户名"
// @Success 200 {object} models.User
// @Failure 400 {object} response.ErrorResponse "无效的用户名"
// @Failure 404 {object} response.ErrorResponse "用户不存在"
// @Router /api/v1/users/username/{username} [get]
func (h *UserHandler) GetUserByUsername(c *gin.Context) {
	username := c.Param("username")
	if username == "" {
		c.JSON(http.StatusBadRequest, response.Fail(http.StatusBadRequest, "username cannot be empty"))
		return
	}

	user, err := h.service.GetUserByUsername(username)
	if err != nil {
		c.JSON(http.StatusNotFound, response.Fail(http.StatusNotFound, "user not found"))
		return
	}

	c.JSON(http.StatusOK, response.Success("success", user))
}

func (h *UserHandler) UserWithOrders(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "invalid ID format"})
		return
	}
	// 2. 调用Service层
	result, err := h.service.UserWithOrders(uint(id))
	if err != nil {
		// 根据错误类型返回不同的状态码
		statusCode := http.StatusInternalServerError
		c.JSON(http.StatusOK, response.Fail(statusCode, err.Error()))
		return
	}

	c.JSON(http.StatusOK, response.Success("success", result))
}
